package com.pn.springboot002_redis.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pn.springboot002_redis.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CacheConfig(cacheNames = "com.pn.user")
public class UserController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping("/login")
    public User login(String username, String password){

        //1:处理请求
        boolean flag = false;
        if("admin".equals(username) && "123456".equals(password)){
            flag = true;
        }

        if(flag){
            return new User(username,password,"张三","西安",25);
        }else{
            return null;
        }

    }

    @RequestMapping("/login2")
    public String login2(String username, String password) throws JsonProcessingException {

        //1:处理请求
        boolean flag = false;
        if("admin".equals(username) && "123456".equals(password)){
            flag = true;
        }

        if(flag){
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            String key = UUID.randomUUID().toString();
            ObjectMapper om = new ObjectMapper();
            String value = om.writeValueAsString(new User(username, password, "张三", "西安", 25));
            ops.set(key,value);
            redisTemplate.expire(key,30, TimeUnit.MINUTES);
            //1:将用户对象保存在redis中
            return key;
        }else{
            return null;
        }
    }

    @RequestMapping("/getUser")
    public String getUser(String uuid){
        //从redis中获取对应的user对象
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String user = ops.get(uuid);

        return user;
    }
}
